package org.nch.videoLauncher.domain;

import org.nch.videoLauncher.domain.Profile;
import org.nch.videoLauncher.domain.VideoItem;
import org.nch.videoLauncher.domain.IPlayable;
import org.nch.videoLauncher.task.ProfileUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: bill
 * Date: Dec 2, 2008
 * Time: 12:02:41 PM
 * To change this template use File | Settings | File Templates.
 */
public class PlayerService {

    private static final String appExecNameMacOSX = "/Applications/VLC.app/Contents/MacOS/VLC";
    private static final String appExecNameLinux = "vlc";
    private static final String urlOpenNameMacOSX = "open";
    private static final String urlOpenNameLinux = "/usr/bin/firefox";
    
    private Profile profile;
    private String baseVideoPath;

    public PlayerService(){
        this.profile = ProfileUtil.getProfile();
        this.baseVideoPath = profile.getBaseVideoPath();
    }

    public PlayerService(Profile profile){
        this.profile = profile;
        this.baseVideoPath = profile.getBaseVideoPath();
    }

    public void playVideoItem(IPlayable vi){

        if (vi.getFileCount() == 1){
            playVideoFromFile(vi.getFilename());
        }

        if (vi.getFileCount() > 1){
            if (createPlaylistForVideoItem(vi)){
                playVideoFromPlaylist(getPlaylistFilename());
            }
        }
    }

    public void playVideoFromFile(String filename){

        String vlcCommand = ProfileUtil.getProfile().getVlcCommand();

        try {
            if (System.getProperty("os.name").equals("Mac OS X")){    // are we running on Mac OS X?
                if (vlcCommand == null || vlcCommand.equals(""))
                    vlcCommand = appExecNameMacOSX;
                Process proc =  Runtime.getRuntime().exec( new String[] { vlcCommand, "--fullscreen", baseVideoPath + File.separator + filename});
            }
            else  if (System.getProperty("os.name").equals("Linux"))   // linux
            {
                if (vlcCommand == null || vlcCommand.equals(""))
                    vlcCommand = appExecNameLinux;
                Process proc =  Runtime.getRuntime().exec( new String[] { vlcCommand, baseVideoPath + File.separator + filename, "--fullscreen"});
            } else
            {
                Process proc =  Runtime.getRuntime().exec( new String[] { vlcCommand, baseVideoPath + File.separator + filename, "--fullscreen"});                
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    public void playVideoFromPlaylist(String playlistFilename){
        try {
            if (System.getProperty("os.name").equals("Mac OS X")){    // are we running on Mac OS X?
                Process proc =  Runtime.getRuntime().exec( new String[] { appExecNameMacOSX, "--fullscreen", playlistFilename});
            }
            else    // assume linux
            {
                Process proc =  Runtime.getRuntime().exec( new String[] { appExecNameLinux, playlistFilename, "--fullscreen"});
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    private String getBaseVideoPath(){

        return baseVideoPath;
    }

    public void openUrl(VideoItem vi){   // TODO:  refactor openURL to get browser command from profile

        String urlCommand = ProfileUtil.getProfile().getUrlCommand();

        try {
            if (vi.getUrl() != null && !vi.getUrl().equals("")){     // make sure we have a non-empty URL string

                if (System.getProperty("os.name").equals("Mac OS X")){    // are we running on Mac OS X?
                    if (urlCommand == null || urlCommand.equals(""))
                        urlCommand = urlOpenNameMacOSX;
                    Process proc =  Runtime.getRuntime().exec( new String[] { urlCommand, vi.getUrl()});
                }
                else if (System.getProperty("os.name").equals("Linux"))    // linux
                {
                    if (urlCommand == null || urlCommand.equals(""))
                        urlCommand = urlOpenNameLinux;
                    Process proc =  Runtime.getRuntime().exec( new String[] { urlCommand, vi.getUrl()});
                } else        // windows
                {
                    Process proc =  Runtime.getRuntime().exec( new String[] { urlCommand, vi.getUrl()});
                }
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    private boolean createPlaylistForVideoItem(IPlayable videoItem){

        File playlistFile = new File(getPlaylistFilename());

        if (playlistFile.exists()){
            playlistFile.delete();
        }

        String playlistContent = getPlaylistContent(videoItem);

        try {
            FileOutputStream outStream = new FileOutputStream(playlistFile);
            outStream.write(playlistContent.getBytes());
            outStream.close();
        } catch (IOException e){
            System.out.println("Could not write to playlist file: " + getPlaylistFilename());
            return false;
        }
        return true;
    }

    private String getPlaylistFilename(){

        StringBuilder playlistFilename = new StringBuilder();
        playlistFilename.append(System.getProperty("user.dir"));
        playlistFilename.append(File.separator);
        playlistFilename.append("videobrain.m3u");
        return playlistFilename.toString();
    }

    private String getPlaylistContent(IPlayable vi){

        StringBuilder content = new StringBuilder();
        List<VideoFile> files = vi.getFiles();

        for (VideoFile vf : files){
            content.append(this.baseVideoPath);
            content.append(File.separator);
            content.append(vf.getFilename());
            content.append("\n");
        }
        return content.toString();

    }

}
